<template>
  <div class="pie-chart" :style="style">
    <KCharts
      ref="pieChartRef"
      :width="width"
      :height="height"
      :option="option"
      v-bind="$attrs"
      over
      :pie-highlight="options.pieHighlight"
      :highlight-index="options.highlightIndex"
      @out="$emit('out')"
      @over="$emit('over', $event)"
      @click="$emit('clicked', $event)"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { createPieOption } from '@/hooks/charts/pie-chart';
import type { Options, BaseNameValueObject } from '@/hooks/charts/type';

defineOptions({ name: 'PieChart' });

interface YData extends BaseNameValueObject {
  color: string;
}
interface Props {
  width: string;
  height: string;
  legend?: any;
  seriesLabel?: Function;
  options?: Options;
  yData: YData[];
}
const props = withDefaults(defineProps<Props>(), {
  legend: {},
  seriesLabel: undefined,
  options: () => {
    return {
      showLegend: true,
      legendPosition: 'bottom',
      pieHighlight: false,
      highlightIndex: 0
    };
  }
});
defineEmits(['clicked', 'out', 'over']);
const option = ref({});
const pieChartRef = ref<any>(null);
const style = computed(() => {
  return {
    width: props.width,
    height: props.height
  };
});

const selectHighlight = (index: number) => {
  pieChartRef.value?.selectHighlight(index);
};

watch(
  () => props.yData,
  (yData) => {
    option.value = createPieOption({
      legend: props.legend,
      seriesLabel: props.seriesLabel,
      options: props.options ?? {},
      yData
    });
  },
  {
    deep: true,
    immediate: true
  }
);

defineExpose({
  selectHighlight
});
</script>

<style lang="scss" scoped>
.pie-chart {
  box-sizing: border-box;
}
</style>
